package com.fastmms.generate;

import com.fastmms.config.FastMmsConfig;
import com.fastmms.utils.ByteUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.List;

public class GenerateUtil {
    public static void merge(String msgPath, List<GenerateMessageBody> bodyList ) throws Exception {
        // 合并文件
        File msgFile = new File(msgPath);
        if (msgFile.exists() && msgFile.isFile()) {
            msgFile.delete();
        }
        msgFile.createNewFile();
        FileOutputStream msgOut = new FileOutputStream(msgFile);
        FileChannel msgOutChannel = msgOut.getChannel();

        // 合并索引
        File idxFile = new File(msgPath.substring(0,msgPath.lastIndexOf(".") ) +  FastMmsConfig.INDEX_SUFFIX );
        if (idxFile.exists() && idxFile.isFile()) {
            idxFile.delete();
        }
        idxFile.createNewFile();
        FileOutputStream idxOut = new FileOutputStream(idxFile);

        // 开始合并数据
        long tempPoint = 0;
        int idxLimit;
        byte[] indexTempByte = null;
        try {
            for (GenerateMessageBody body : bodyList) {
                String subPath = body.getFilePath();
                FileInputStream tempStream = null;
                FileChannel channel = null;
                try {
                    // 开始读取合并消息
                    File tempFile = new File(subPath);
                    if (!tempFile.exists() || tempFile.isDirectory()) {
                        continue;
                    }
                    tempStream = new FileInputStream(tempFile);
                    channel = tempStream.getChannel();
                    channel.transferTo(0,tempFile.length() , msgOutChannel);

                    // 合并索引
                    List<GenerateIndexData> indexDataList = body.getIndexDataList();
                    int idxSize = indexDataList.size();
                    // index + msgNo = 16
                    idxLimit = idxSize * 16;
                    if( indexTempByte == null || indexTempByte.length < idxLimit ){
                        indexTempByte = new byte[ idxLimit ];
                    }
                    int destPos=0;
                    for (int i = 0; i < idxSize; i++) {
                        GenerateIndexData indexData = indexDataList.get(i);
                        byte[] idxByte = ByteUtil.longToBytesBig( indexData.getBlockIndex() + tempPoint );
                        System.arraycopy( idxByte ,0, indexTempByte, destPos , 8 );
                        destPos += 8;
                        byte[] startNoByte = ByteUtil.longToBytesBig( indexData.getMsgStartNo() );
                        System.arraycopy( startNoByte ,0, indexTempByte, destPos , 8 );
                        destPos += 8;
                    }
                    idxOut.write( indexTempByte , 0 , idxLimit );
                    idxOut.flush();
                    tempPoint += tempFile.length();

                    channel.close();
                    tempStream.close();
                    channel = null;
                    tempStream = null;
                    tempFile.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if(channel != null){
                        channel.close();
                    }
                    if(tempStream != null){
                        tempStream.close();
                    }
                }
            }
        }finally {
            msgOutChannel.close();
            msgOut.close();
            idxOut.close();
        }
    }
    /*public static void merge(String msgPath, List<GenerateMessageBody> bodyList ) throws Exception {
        // 合并文件
        File msgFile = new File(msgPath);
        if (msgFile.exists() && msgFile.isFile()) {
            msgFile.delete();
        }
        msgFile.createNewFile();
        RandomAccessFile msgAccessFile = new RandomAccessFile(msgFile, "rw");

        // 合并索引
        File idxFile = new File(msgPath.substring(0,msgPath.lastIndexOf(".") ) + ".index" );
        if (idxFile.exists() && idxFile.isFile()) {
            idxFile.delete();
        }
        idxFile.createNewFile();
        RandomAccessFile idxAccessFile = new RandomAccessFile(idxFile, "rw");

        // 开始合并数据
        byte[] copyData = new byte[2048];
        long tempPoint = 0;
        int idxLimit;
        byte[] indexTempByte = null;
        for (GenerateMessageBody body : bodyList) {
            String subPath = body.getFilePath();
            try {
                // 开始读取合并消息
                File tempFile = new File(subPath);
                if (!tempFile.exists() || tempFile.isDirectory()) {
                    continue;
                }
                FileInputStream tempStream = new FileInputStream(tempFile);
                int size;
                while ((size = (tempStream.read(copyData))) > 0) {
                    msgAccessFile.write(copyData, 0, size);
                }
                // 合并索引
                List<Long> indexList = body.getIndexList();
                int idxSize = indexList.size();
                idxLimit = idxSize * 8;
                if( indexTempByte == null || indexTempByte.length < idxLimit ){
                    indexTempByte = new byte[ idxLimit ];
                }
                for (int i = 0; i < idxSize; i++) {
                    Long index = indexList.get(i);
                    byte[] idxByte = ByteUtil.longToBytesBig( index + tempPoint );
                    System.arraycopy( idxByte ,0, indexTempByte,i * idxByte.length , idxByte.length );
                }
                idxAccessFile.write(indexTempByte , 0 , idxLimit );
                tempPoint += tempFile.length();
                msgAccessFile.length();
                idxAccessFile.length();
                tempFile.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        msgAccessFile.close();
        idxAccessFile.close();
    }*/

}
